package com.six.order.controller;

import com.six.core.util.JwtUtil;
import com.six.core.util.WebUtil;
import com.six.core.vo.Result;
import com.six.order.service.GoodsCartService;
import com.six.order.vo.AddGoodsCartVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * @author: WangPeng
 * @createTime: 2023/03/03 15:48
 * @description:
 * @version: v1.0
 */
@RestController
@RequestMapping("/order/goodCart")
public class GoodsCartController {

    @Autowired
    private GoodsCartService goodsCartService;

    private Integer getUserid(){
        HttpServletRequest request = WebUtil.getRequest();
        String token = request.getHeader("token");
        if (token!=null){
            Map<String, Object> map = JwtUtil.decodeJWT(token);
            return (Integer) map.get("tbUserid");
        }
        return null;
    }

    /** 获取用户购物中物品的条数，根据userid进行查询 */
    @PostMapping("/getGoodsCartNum")
    public Result getGoodsCartNum(){
        return goodsCartService.getGoodsCartNum(getUserid());
    }

    /** 通过userid获取当前用户的购物车列表 */
    @PostMapping("/getListByUserid")
    public Result getListByUserid(){
        return goodsCartService.getListByUserid(getUserid());
    }

    /** 根据id删除购物车的单个商品 */
    @PostMapping("/deleteOneById")
    public Result deleteOneById(Integer id){
        return goodsCartService.deleteOneById(id);
    }

    /** 用户批量删除购物车的商品 */
    @PostMapping("/deleteByIds")
    public Result deleteByIds(@RequestBody List<Integer> ids){
        return goodsCartService.deleteByIds(ids);
    }

    /** 点击加减按钮的时候修改购物车中的数量 */
    @PostMapping("/updateNum")
    public Result updateNum(Integer id,Integer goodsNum,Double totalPrice){
        return goodsCartService.updateNum(id,goodsNum,totalPrice);
    }

    /** 向购物车中添加商品，首先根据userid，goodsid进行数据库查询，
     *  判断这个物品是否在数据库中，若是在就增加数量，不在就添加进购物车。*/
    @PostMapping("/addGoodsCart")
    public Result addGoodsCart(@RequestBody AddGoodsCartVo addGoodsCartVo) {
        HttpServletRequest request = WebUtil.getRequest();
        String token = request.getHeader("token");
        Map<String, Object> map = JwtUtil.decodeJWT(token);
        Integer userid = (Integer) map.get("tbUserid");
        addGoodsCartVo.setUserid(userid);
        addGoodsCartVo.setTotal(addGoodsCartVo.getGoodsNum()* addGoodsCartVo.getPrice());
        return goodsCartService.addGoodsCart(addGoodsCartVo);
    }
}
